const express = require("express");
const router = express.Router();
const handle = require("../routes_handle/doc");
const { CODE, Response } = require("../utils/response");
const { query } = require("../utils/db");

// 1. 获取文档树
router.get("/doc/getDocTree", async (req, res, next) => {
  try {
    const { FSpaceId } = req.query;
    const userId = req.user.userId; // 假设用户信息在req.user中
    const isAdmin = req.query.isAdmin || false; // 从用户信息获取管理员状态

    if (!FSpaceId) {
      return res
        .status(CODE.BAD_REQUEST)
        .json(Response.error(CODE.BAD_REQUEST, "缺少空间ID"));
    }

    const result = await handle.getDocTree(FSpaceId, userId, isAdmin);
    res.status(CODE.SUCCESS).json(Response.success(result, "获取成功"));
  } catch (err) {
    next(err);
  }
});

// 2.设置文档可见性（新增FInheritParent参数）
router.post("/doc/setVisibility", async (req, res, next) => {
  try {
    const { FDocId, FIsPublic, FInheritParent, FUserIds, isAdmin, FParentId } =
      req.body;
    const isAdminBool = isAdmin === "true";
    if (!FDocId || FIsPublic === undefined || FInheritParent === undefined) {
      return res
        .status(CODE.BAD_REQUEST)
        .json(Response.error(CODE.BAD_REQUEST, "缺少必要参数"));
    }

    // 权限检查：用户是否是空间管理员或文档创建者
    const [doc] = await query(
      "SELECT FAuthorId FROM t_doc_nodes WHERE FId = ?",
      [FDocId]
    );
    if (!doc) {
      return res
        .status(CODE.NOT_FOUND)
        .json(Response.error(CODE.NOT_FOUND, "文档不存在"));
    }

    // 检查用户权限
    const isAuthor = doc.FAuthorId === req.user.userId;
    const isSpaceAdmin = await checkSpaceAdmin(doc.FSpaceId, req.user.userId);

    if (!isAuthor && !isSpaceAdmin && !isAdminBool) {
      return res
        .status(CODE.FORBIDDEN)
        .json(Response.error(CODE.FORBIDDEN, "无权限操作"));
    }

    const result = await handle.setDocVisibility({
      FDocId,
      FIsPublic,
      FInheritParent,
      FUserIds: FUserIds || [],
      FParentId,
    });

    res.status(CODE.SUCCESS).json(Response.success(result, "设置成功"));
  } catch (err) {
    next(err);
  }
});

// 3.获取文档可见性设置
router.get("/doc/getVisibility", async (req, res, next) => {
  try {
    const { FDocId, isAdmin } = req.query;
    const isAdminBool = isAdmin === "true";

    if (!FDocId) {
      return res
        .status(CODE.BAD_REQUEST)
        .json(Response.error(CODE.BAD_REQUEST, "缺少文档ID"));
    }

    // 检查用户是否有权限查看该文档
    const [doc] = await query(
      "SELECT FSpaceId FROM t_doc_nodes WHERE FId = ?",
      [FDocId]
    );
    if (!doc) {
      return res
        .status(CODE.NOT_FOUND)
        .json(Response.error(CODE.NOT_FOUND, "文档不存在"));
    }
    let hasAccess = false;
    if (isAdminBool) {
      hasAccess = true;
    } else {
      hasAccess = await checkDocAccess(FDocId, req.user.userId);
    }

    if (!hasAccess) {
      return res
        .status(CODE.FORBIDDEN)
        .json(Response.error(CODE.FORBIDDEN, "无权限查看"));
    }

    const result = await handle.getDocVisibility(FDocId);
    res.status(CODE.SUCCESS).json(Response.success(result, "获取成功"));
  } catch (err) {
    next(err);
  }
});

// 4. 新增文档节点
router.post("/doc/addDocNode", async (req, res, next) => {
  try {
    const { FSpaceId, FParentId, FTitle, FType, FContent, isAdmin } = req.body;
    const FAuthorId = req.user.userId; // 从用户信息获取作者ID
    

    if (!FSpaceId || !FTitle || !FType) {
      return res
        .status(CODE.BAD_REQUEST)
        .json(Response.error(CODE.BAD_REQUEST, "缺少必要参数"));
    }

    // 检查用户是否有权限在该空间创建文档
    const hasPermission = await checkSpacePermission(FSpaceId, req.user.userId);
    if (!hasPermission && !isAdmin) {
      return res
        .status(CODE.FORBIDDEN)
        .json(Response.error(CODE.FORBIDDEN, "无权限操作"));
    }

    const result = await handle.addDocNode({
      FSpaceId,
      FParentId,
      FTitle,
      FType,
      FContent,
      FAuthorId,
    });

    res.status(CODE.SUCCESS).json(Response.success(result, "添加成功"));
  } catch (err) {
    next(err);
  }
});

// 5. 编辑文档节点
router.post("/doc/updateDocNode", async (req, res, next) => {
  try {
    const { FId, FTitle, FContent, isAdmin } = req.body;
    const isAdminBool = isAdmin === "true";
    if (!FId) {
      return res
        .status(CODE.BAD_REQUEST)
        .json(Response.error(CODE.BAD_REQUEST, "缺少节点ID"));
    }

    // 检查用户是否有权限编辑该文档
    const [doc] = await query(
      "SELECT FAuthorId, FSpaceId FROM t_doc_nodes WHERE FId = ?",
      [FId]
    );
    if (!doc) {
      return res
        .status(CODE.NOT_FOUND)
        .json(Response.error(CODE.NOT_FOUND, "文档不存在"));
    }

    const isAuthor = doc.FAuthorId === req.user.userId;
    const isSpaceAdmin = await checkSpaceAdmin(doc.FSpaceId, req.user.userId);

    if (!isAuthor && !isSpaceAdmin && !isAdminBool) {
      return res
        .status(CODE.FORBIDDEN)
        .json(Response.error(CODE.FORBIDDEN, "无权限操作"));
    }

    const result = await handle.updateDocNode({ FId, FTitle, FContent });
    res.status(CODE.SUCCESS).json(Response.success(result, "更新成功"));
  } catch (err) {
    next(err);
  }
});

// 6. 删除文档节点
router.post("/doc/deleteDocNode", async (req, res, next) => {
  try {
    const { FId } = req.body;
    if (!FId) {
      return res
        .status(CODE.BAD_REQUEST)
        .json(Response.error(CODE.BAD_REQUEST, "缺少节点ID"));
    }

    // 检查用户是否有权限删除该文档
    const [doc] = await query(
      "SELECT FAuthorId, FSpaceId FROM t_doc_nodes WHERE FId = ?",
      [FId]
    );
    if (!doc) {
      return res
        .status(CODE.NOT_FOUND)
        .json(Response.error(CODE.NOT_FOUND, "文档不存在"));
    }

    const isAuthor = doc.FAuthorId === req.user.userId;
    const isSpaceAdmin = await checkSpaceAdmin(doc.FSpaceId, req.user.userId);

    if (!isAuthor && !isSpaceAdmin && !req.user.isAdmin) {
      return res
        .status(CODE.FORBIDDEN)
        .json(Response.error(CODE.FORBIDDEN, "无权限操作"));
    }

    const result = await handle.deleteDocNode(FId);
    res.status(CODE.SUCCESS).json(Response.success(result, "删除成功"));
  } catch (err) {
    next(err);
  }
});

// 7. 添加文档阅读记录
router.post("/doc/addReadHistory", async (req, res, next) => {
  try {
    const { FDocId } = req.body;
    const FUserId = req.user.userId;

    if (!FDocId) {
      return res
        .status(CODE.BAD_REQUEST)
        .json(Response.error(CODE.BAD_REQUEST, "缺少文档ID"));
    }

    await handle.addReadHistory(FDocId, FUserId);
    res.status(CODE.SUCCESS).json(Response.success(null, "阅读记录添加成功"));
  } catch (err) {
    next(err);
  }
});

// 8. 获取用户阅读历史记录
router.get("/doc/getReadHistory", async (req, res, next) => {
  try {
    const { limit } = req.query;
    const FUserId = req.user.userId;

    const result = await handle.getUserReadHistory(FUserId, parseInt(limit) || 10);
    res.status(CODE.SUCCESS).json(Response.success(result, "获取成功"));
  } catch (err) {
    next(err);
  }
});

// 9. 删除用户阅读记录
router.post("/doc/deleteReadHistory", async (req, res, next) => {
  try {
    const { FDocId } = req.body;
    const FUserId = req.user.userId;

    if (!FDocId) {
      return res
        .status(CODE.BAD_REQUEST)
        .json(Response.error(CODE.BAD_REQUEST, "缺少文档ID"));
    }

    const result = await handle.deleteUserReadHistory(FUserId, FDocId);
    if (!result) {
      return res
        .status(CODE.NOT_FOUND)
        .json(Response.error(CODE.NOT_FOUND, "阅读记录不存在"));
    }

    res.status(CODE.SUCCESS).json(Response.success(null, "删除成功"));
  } catch (err) {
    next(err);
  }
});

// 辅助函数：检查用户是否是空间管理员
async function checkSpaceAdmin(FSpaceId, FUserId) {
  const [result] = await query(
    "SELECT 1 FROM t_space_admins WHERE FSpaceId = ? AND FUserId = ?",
    [FSpaceId, FUserId]
  );
  return !!result;
}

// 辅助函数：检查用户是否有空间权限
async function checkSpacePermission(FSpaceId, FUserId) {
  // 检查用户是否是空间成员或管理员
  const [result] = await query(
    `SELECT 1 FROM t_space_admins WHERE FSpaceId = ? AND FUserId = ?
     UNION
     SELECT 1 FROM t_user_space_favorites WHERE FSpaceId = ? AND FUserId = ?`,
    [FSpaceId, FUserId, FSpaceId, FUserId]
  );
  return !!result;
}

// 辅助函数：检查用户是否有文档访问权限
async function checkDocAccess(FDocId, FUserId) {
  const [result] = await query(
    `SELECT 1 FROM t_doc_nodes d
     LEFT JOIN t_visibility_settings v ON d.FId = v.FDocId
     LEFT JOIN t_visibility_users vu ON v.FId = vu.FVisibilityId
     WHERE d.FId = ? AND (v.FIsPublic = 1 OR vu.FUserId = ?)`,
    [FDocId, FUserId]
  );
  return !!result;
}




module.exports = router;
